package com.caohx.bms.service;

import com.caohx.bms.pojo.User;
import com.caohx.bms.pojo.dto.LoginDto;
import com.caohx.bms.pojo.dto.UserDto;
import com.caohx.bms.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service  //表明这是一个spring的bean 由spring 负责创建 管理对象
public class UserService implements IUserService {

    @Autowired
    UserRepository userrepository ;

    @Override
    public User add(UserDto user) {
        //调用数据访问类的添加功能
        User userpojo = new User();
        BeanUtils.copyProperties(user,userpojo);
       return  userrepository.save(userpojo);
    }

    @Override
    public User get(Integer userid) {
      return  userrepository.findById(userid).orElseThrow(()->{ throw new IllegalArgumentException("用户不存在，参数异常！");});

    }

    @Override
    public User edit(UserDto user) {
        //调用数据访问类的添加功能
//        User userpojo = new User();
//        BeanUtils.copyProperties(user,userpojo);
//        return  userrepository.save(userpojo);


        // 根据ID查找要编辑的用户
        User existingUser = userrepository.findById(user.getUserID())
                .orElseThrow(() -> new IllegalArgumentException("用户不存在，参数异常！"));
        // 更新用户的属性
        BeanUtils.copyProperties(user, existingUser, "id"); // 排除ID不进行拷贝

        // 保存更新后的用户
        return userrepository.save(existingUser);
    }

    @Override
    public void delete(Integer userid) {
        // 根据ID查找
        User existingUser = userrepository.findById(userid)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在，参数异常！"));
         userrepository.deleteById(userid);
         return  ;
    }

    @Override
    public boolean existsByUserName(String userName) {
        return userrepository.existsByUserName(userName);
    }

    @Override
    public boolean existsByUserEmail(String userEmail) {
        return userrepository.existsByUserEmail(userEmail);
    }

    // 登录用户
    @Override
    public boolean login(LoginDto loginDto) {
        User user = userrepository.findByUserName(loginDto.getUserName());
        //用户名存在，且密码正确
       if (user != null && loginDto.getUserPassword().equals(user.getUserPassword())) {
            return true;
        }
        return false;
    }

    @Override
    public Page<User> listUsers(Pageable pageable) {
        return userrepository.findAll(pageable);
    }

  //  @Override
 //  public List<User> getAllUsers() {
  //      return (List<User>) userrepository.findAll();
 //   }


}
